package com.wonders.hs.pd.mm.web.controller;

import com.wonders.hs.pd.mm.web.bean.UserModel;
import com.wonders.hs.pd.mm.web.config.SystemConfig;
import com.wonders.hs.pd.mm.web.utils.HttpRequestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author banglong
 * @date 2016/8/17
 */
@Controller
public class RouterController {

  private final static Logger logger = LoggerFactory.getLogger(RouterController.class);

  // 全局的用于保存 用户名 和 session 映射关系的 map
//    private static LoadingCache<String, HttpSession> sessionMap;
//    private static Map<String, HttpSession> cacheMap = Maps.newHashMap();
//
//    static {
//        sessionMap = CacheBuilder.newBuilder()
//                .maximumSize(1000)
//                .expireAfterAccess(5, TimeUnit.MINUTES)
//                .expireAfterWrite(5, TimeUnit.MINUTES)
//                .build(
//                        new CacheLoader<String, HttpSession>() {
//                            public HttpSession load(String key) throws Exception {
//                                return cacheMap.get(key);
//                            }
//                        });
//    }

  // 测试 首页
  @RequestMapping("/indexTest")
  public String indexTest(HttpServletRequest request) {
    String message = "Hello world";
    request.setAttribute("message", message);
    return "indexTest";
  }

  /**
   * 登陆页
   */
  @RequestMapping("/login")
  public String login() {
    return "login";
//        return "forward";
  }

  /**
   * 登录之后的跳转验证 判断是否有第二个用户登录
   */
  @RequestMapping("/loginAuthentication")
  public String loginAuthentication(HttpSession httpSession, HttpServletRequest request) {
    try {
      // 设置session过期时间
      httpSession.setMaxInactiveInterval(Integer.parseInt(SystemConfig.SESSION_TIMEOUT));
      UserModel userInfo = (UserModel) httpSession.getAttribute("currentUser");

//            HttpSession oldSession = sessionMap.get(userInfo.getYgid());
//            if (oldSession != null && !oldSession.equals(httpSession)) {
//                oldSession.setAttribute("currentUser", null);
//            }
//            oldSession = null;
//            sessionMap.put(userInfo.getYgid(), httpSession);
      request.setAttribute("username", userInfo.getXm());
    } catch (Exception e) {
      logger.error("/loginAuthentication", e);
    }
    return "redirect:/index";
  }

  /**
   * 首页
   */
  @RequestMapping("/index")
  public String index(HttpSession httpSession, HttpServletRequest request) {

    UserModel userInfo = (UserModel) httpSession.getAttribute("currentUser");

    // 判断用户信息是否保存 防止session 权限判断
    if (userInfo == null) {
      return "redirect:/login";
    }
//    // 更新登录信息
//    String url = SystemConfig.API_ADDRESS + "UserLoginInfoManager" + "/updateUserLoginInfo"; // 访问地址
//    Map<String, Object> params = new HashMap<>();
//    params.put("userLoginInfo", userInfo); // 参数
//    String result = HttpRequestUtils.sendPost(url, params);
    request.setAttribute("username", userInfo.getXm());
    return "index";
  }

  /**
   * 首页登出
   */
  @RequestMapping("/logout")
  public String logout(HttpSession httpSession, HttpServletRequest request) {
    try {
//            UserModel userInfo = (UserModel) httpSession.getAttribute("currentUser");
//            sessionMap.put(userInfo.getYgid(), null);
      httpSession.invalidate();
    } catch (Exception e) {
      logger.error("/logout", e);
    }
    return "redirect:/login";
  }

  /**
   * 物品查询页面
   */
  @RequestMapping("/goodsQuery")
  public String goodsQuery() {
    // todo
    return "goodsQuery";
  }

  /**
   * 报表导出页面
   * 不良记录查询
   */
  @RequestMapping("/badRecord")
  public String badRecord(Model model) {
    Map<String, String> param = new HashMap<>();
    param.put("title", "供应商不良记录导出");
    param.put("path", "badRecord");
    model.addAttribute("accessParam", param);
    return "report";
  }

  /**
   * 报表导出页面
   * 医保代码导出
   */
  @RequestMapping("/medicareCode")
  public String medicareCodeExport(Model model) {
    Map<String, String> param = new HashMap<>();
    param.put("title", "医保代码导出");
    param.put("path", "medicareCode");
    model.addAttribute("accessParam", param);
    return "report";
  }

  /**
   * 报表导出页面
   * 医保代码导出
   */
  @RequestMapping("/reportIndex")
  public String reportIndex(Model model) {
    Map<String, String> param = new HashMap<>();
    param.put("title", "报表预览页");
    param.put("path", "index");
    model.addAttribute("accessParam", param);
    return "report";
  }

//  /**
//   * 账户余额查询 todo 直接采用 html静态文件的方式 xxx/html/balanceQuery.html
//   */
//  @RequestMapping("/balanceQuery")
//  public String balanceQuery() {
//    return "balanceQuery";
//  }
}
